package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Additive;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Foodadditive;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("FoodadditiveService")
@Transactional

public class FoodadditiveServiceImpl extends CmiEmaService implements FoodadditiveService {
	public FoodadditiveServiceImpl() {
	}

	@Transactional
	public Foodadditive saveFoodadditive(Foodadditive foodadditive) {

		if (foodadditive.getId() == null) {
			Additive additive = additiveDAO.findAdditiveById(foodadditive.getAdditive().getId());
			Food food = foodDAO.findFoodById(foodadditive.getFood().getId());

			Foodadditive existingFoodadditive = foodadditiveDAO.findFoodadditiveByPhysicalPrimaryKey(food.getId(),
					additive.getId(), foodadditive.getContent());

			foodadditive.setAdditive(additive);
			foodadditive.setFood(food);

			if (isEquals(foodadditive, existingFoodadditive)) {
				return existingFoodadditive;
			}

			foodadditive = foodadditiveDAO.store(foodadditive);
			foodadditiveDAO.flush();

		} else {
			Foodadditive existingFoodadditive = foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditive.getId());

			foodadditive = foodadditiveDAO.store(foodadditive);
			foodadditiveDAO.flush();
		}

		return foodadditive;
	}

	public void deleteFoodadditive(Foodadditive foodadditive) {
		foodadditiveDAO.remove(foodadditive);
		foodadditiveDAO.flush();
	}

	@Transactional
	public void deleteFoodadditives(Set<Integer> deleteFoodadditivesId) {
		Query query = foodadditiveDAO.createNamedQuery("deleteFoodadditivesById", -1, -1);
		query.setParameter(1, deleteFoodadditivesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Foodadditive> loadFoodadditives() {
		return foodadditiveDAO.findAllFoodadditives();

	}

	@Transactional
	public Set<Foodadditive> loadReferenceFoodadditives(Set<Foodadditive> foodadditives) {
		Iterator<Foodadditive> foodadditivesIterator = foodadditives.iterator();
		Set<Foodadditive> referencedFoodadditives = new HashSet<>();
		while (foodadditivesIterator.hasNext()) {
			Foodadditive currentFoodadditive = foodadditivesIterator.next();

		}
		return referencedFoodadditives;
	}

	public Set<Foodadditive> loadFoodadditivesByIdSet(Set<Integer> foodadditiveIdSet) {

		Iterator<Integer> foodadditiveIdIterator = foodadditiveIdSet.iterator();
		Set<Foodadditive> foodadditiveSet = new HashSet<>();
		while (foodadditiveIdIterator.hasNext()) {
			Integer id = foodadditiveIdIterator.next();
			Foodadditive currentFoodadditive = foodadditiveDAO.findFoodadditiveById(id);
			foodadditiveSet.add(currentFoodadditive);
		}
		return foodadditiveSet;
	}

	@Transactional
	public List<Foodadditive> findAllFoodadditives(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Foodadditive>(foodadditiveDAO.findAllFoodadditives(startResult, maxRows));
	}

	@Transactional
	public Foodadditive findFoodadditiveByPrimaryKey(Integer id) {
		return foodadditiveDAO.findFoodadditiveByPrimaryKey(id);
	}

	@Transactional
	public Integer countFoodadditives() {
		return ((Long) foodadditiveDAO.createQuerySingleResult("select count(o) from Foodadditive o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countFoodadditives(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Foodadditive.class);
		return ((Long) foodadditiveDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countFoodadditivesByName(String queryName) {
		Query query = foodadditiveDAO.createNamedQuery("countFoodadditivesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodadditivesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Foodadditive.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFoodadditiveObjectReferencedSet(Foodadditive foodadditive) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (foodadditive.getAdditive() != null) {

			Set<Integer> additiveIds = new HashSet<Integer>();
			additiveIds.add(foodadditive.getAdditive().getId());
			objectReferencedSetMap.put("additiveIds", additiveIds);
		}
		if (foodadditive.getFood() != null) {

			Set<Integer> foodIds = new HashSet<Integer>();
			foodIds.add(foodadditive.getFood().getId());
			objectReferencedSetMap.put("foodIds", foodIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFoodadditiveClassReferencedSet(Foodadditive foodadditive) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("additives", additiveDAO.findAllAdditives());
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Foodadditive foodadditive, Object obj) {
		if (obj == foodadditive)
			return true;
		if (!(obj instanceof Foodadditive))
			return false;
		Foodadditive comparedFoodadditive = (Foodadditive) obj;
		if (!CheckPropertyEqual(foodadditive.getFood().getId(), comparedFoodadditive.getFood().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodadditive.getAdditive().getId(), comparedFoodadditive.getAdditive().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodadditive.getContent(), comparedFoodadditive.getContent())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

